package com.jtw.common.util;

import com.esotericsoftware.kryo.Kryo;

import java.security.MessageDigest;
import java.util.*;
import java.util.stream.Collectors;

public class BaseUtil {

	public static String MD5(String data) {
		StringBuilder sb = new StringBuilder();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(data.getBytes("UTF-8"));
	        for (byte item : array) {
	            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return sb.toString();
    }

	public static String getId() {
		String s = DateUtil.format(new Date(), DateUtil.YMDHMSS);
		String s1 = captchaNumber(8);
		return s + s1;
	}

	/**
	 * 返回指定长度的随机数
	 * @param length
	 * @return
	 */
	public static String captchaNumber(int length) {
		StringBuilder sb = new StringBuilder();
		Random rand = new Random();
		for (int i = 0; i < length; i++) {
			sb.append(rand.nextInt(10));
		}
		return sb.toString();
	}

	/**
	 * 将字母转换成数字
	 * @param input
	 */
	public static String letterToNum(String input) {
		StringBuffer sb = new StringBuffer();
		for (byte b : input.getBytes()) {
			sb.append(b);
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		String ca = letterToNum("0102020C");
		System.out.println(ca);
		System.out.println(new String(hexStr2Bytes(ca)));

		ca = letterToNum("010G");
		System.out.println(ca);
		System.out.println(new String(hexStr2Bytes(ca)));
	}

	public static byte[] hexStr2Bytes(String src) {
		int m=0,n=0;
		int l=src.length()/2;
		byte[] ret = new byte[l];
		for (int i = 0; i < l; i++) {
			m=i*2+1;
			n=m+1;
			ret[i] = Byte.valueOf(src.substring(i*2, m)+src.substring(m,n));
		}
		return ret;
	}
}
